import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/stores/modules/userStore';
import router from '@/router';

const request = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 50000,
});

request.interceptors.request.use(
  (config) => {
    const userStore = useUserStore();
    const token = userStore.userInfo.token;
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (err) => {
    return Promise.reject(err);
  },
);

request.interceptors.response.use(
  (res) => {
    return res;
  },
  (err) => {
    ElMessage({
      message: err.response.data.message,
      type: 'error',
    });

    const userStore = useUserStore();
    if (err.response.status === 401) {
      userStore.clearUserInfo();
      router.push('/login');
    }
    return Promise.reject(err);
  },
);

export default request;
